package fr.cephb.locustree;

import java.io.Serializable;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

import fr.cephb.berkeleydb.binding.JSONBinding;
import fr.cephb.json.JSONBuilder;
import fr.cephb.json.JSONable;
import fr.cephb.util.StringUtils;

/**
 * ChromInfo
 *
 */
public class ChromInfo
	implements Serializable,JSONable
	{
	private static final long serialVersionUID = 1L;
	private Integer organismId;
	private Integer id;
	private String name;
	private Object json;
	private int length=0;
	
	public static class Binding
	extends TupleBinding<ChromInfo>
		{
		private JSONBinding jsonBinding= new JSONBinding();
		@Override
		public ChromInfo entryToObject(TupleInput in)
			{
			ChromInfo c= new ChromInfo(in.readInt(),in.readInt(),in.readString());
			c.setLength(in.readInt());
			c.setObject(jsonBinding.entryToObject(in));
			return c;
			}
		@Override
		public void objectToEntry(final ChromInfo o, TupleOutput out)
			{
			out.writeInt(o.getId()).
				writeInt(o.getOrganismId()).
				writeString(o.getName()).
				writeInt(o.getLength());
			jsonBinding.objectToEntry(o.getObject(), out);
			}
		}
	
	public ChromInfo(int id,int orgId,String name)
		{
		assert(id>0);
		assert(orgId>0);
		assert(!StringUtils.isEmpty(name));
		this.id=id;
		this.organismId=orgId;
		this.name=name;
		}
	
	public Integer getOrganismId()
		{
		return organismId;
		}
	public Integer getId()
		{
		return id;
		}
	public String getName()
		{
		return name;
		}
	
	public void setLength(int length)
		{
		this.length = length;
		}
	
	public int getLength()
		{
		return length;
		}
	
	public Object getObject()
		{
		return json;
		}
	
	public void setObject(Object json)
		{
		this.json = json;
		}
	
	@Override
	public int hashCode()
		{
		final int prime = 31;
		int result = 1;
		result = prime * result + id.hashCode();
		return result;
		}

	@Override
	public boolean equals(Object obj)
		{
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		ChromInfo other = (ChromInfo) obj;
		if (!id.equals(other.id)) return false;
		return true;
		}

	@Override
	public String toJSON()
		{
		return new JSONBuilder().
				put("id", getId()).
				put("organism-id", getOrganismId()).
				put("name", getName()).
				put("length", getLength()).
				put("metadata", getObject()).
				getString();
		}
	
	@Override
	public String toString()
		{
		return toJSON();
		}
	}
